package io.sdl.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.sdl.common.constant.UrlConstants;
import io.sdl.common.sys.dto.ConversationDTO;
import io.sdl.common.sys.dto.SdlPatientDTO;
import io.sdl.common.sys.dto.SdlSessionMessageDTO;
import io.sdl.common.sys.entity.RequestMessage;
import io.sdl.common.sys.entity.ResponseMessage;
import io.sdl.common.sys.entity.SdlDoctorPatientSessionEntity;
import io.sdl.common.sys.entity.SdlSessionMessageEntity;
import io.sdl.common.sys.service.SdlDoctorPatientSessionService;
import io.sdl.common.sys.service.SdlSessionMessageService;
import io.sdl.common.sys.service.impl.OnlineUserService;
import io.sdl.common.sys.vo.ConcatenatedVo;
import io.sdl.common.utils.IdPairLookupUtils;
import io.sdl.common.utils.Result;
import io.sdl.config.WebSocketConfig;
import io.sdl.entity.TokenEntity;
import io.sdl.entity.UserEntity;
import io.sdl.service.TokenService;
import io.sdl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class ChatController {

	@Autowired
	private SimpMessagingTemplate messagingTemplate;

	@Autowired
	private SdlSessionMessageService sdlSessionMessageService;

	@Autowired
	private SdlDoctorPatientSessionService sdlDoctorPatientSessionService;

	@Autowired
	private OnlineUserService onlineUserService;

	@Autowired
	private UserService userService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private WebSocketConfig webSocketConfig;

	@GetMapping("/send-to-user/{userId}")
	public ResponseEntity<String> sendTestMessage(
			@PathVariable String userId,
			@RequestParam(defaultValue = "测试消息") String content) {

		String destination = "/queue/messages";
		Map<String, Object> message = Map.of(
				"timestamp", System.currentTimeMillis(),
				"content", content
		);

		// 实际发送
		messagingTemplate.convertAndSendToUser(userId, destination, message);

		// 打印路由信息
		String actualPath = "/queue/messages-user" + userId;
		System.out.printf("消息路由路径: %s -> %s%n",
				"/user/" + userId + destination,
				actualPath);

		return ResponseEntity.ok("已发送至: " + actualPath);
	}

	@MessageMapping("/hello") // 处理/app/hello
	@SendToUser("/topic/greetings") // 广播到/topic/greetings
	public String handleMessage(ResponseMessage message) {
		System.out.println("收到客户端消息: " + message.getContent());
		return "服务端回复: ces" + message.getContent() + " (处理时间: " + LocalDateTime.now() + ")";
	}

	@MessageMapping("/chat.sendPrivateMessage")
	@SendToUser("/queue/messages") // 发送给特定用户
	public SdlSessionMessageDTO sendPrivateMessage(@Payload SdlSessionMessageDTO chatMessage) {
		//数据持久化
		SdlDoctorPatientSessionEntity conversation = sdlDoctorPatientSessionService.getConversation(chatMessage.getConversationId());

		SdlSessionMessageEntity sdlSessionMessageEntity = new SdlSessionMessageEntity();

		List<SdlSessionMessageEntity> entity = sdlSessionMessageService.verificationCard(chatMessage.getContent());
		//如果是患者卡片类型的消息,并且卡片存在则不需要在保存此条卡片消息
		if (chatMessage.getMessageType().equals("patient") && entity != null) {
			return chatMessage;
		}
		sdlSessionMessageEntity.setSessionId(conversation.getSessionId());
		sdlSessionMessageEntity.setSenderId(chatMessage.getSenderId());
		sdlSessionMessageEntity.setReceiverId(chatMessage.getReceiverId());
		sdlSessionMessageEntity.setMessageType(chatMessage.getMessageType());
		sdlSessionMessageEntity.setContent(chatMessage.getContent());
		sdlSessionMessageEntity.setSendTime(new Date());
		sdlSessionMessageEntity.setStatus(2);
		sdlSessionMessageService.insert(sdlSessionMessageEntity);

		return chatMessage;
	}

}